package authority

import (
	"context"

	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/enum/errorcode"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/backend/rpc/backendclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type ApiAuthorityLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewApiAuthorityLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ApiAuthorityLogic {
	return &ApiAuthorityLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ApiAuthorityLogic) ApiAuthority(req *types.ApiAuthorityReq) (resp *types.BaseMsgResp, err error) {
	if req.RoleId == nil || *req.RoleId == 0 {
		return nil, errorx.NewCodeError(errorcode.InvalidArgument,
			l.svcCtx.Trans.Trans(l.ctx, "common.validationError"))
	}

	role, err := l.svcCtx.BackendRpc.GetRoleById(l.ctx, &backendclient.IDReq{
		Id: *req.RoleId,
	})
	if err != nil {
		return
	}

	if role.Code == nil || len(*role.Code) == 0 {
		return nil, errorx.NewCodeError(errorcode.InvalidArgument,
			l.svcCtx.Trans.Trans(l.ctx, "common.validationError"))
	}

	//clear old policies
	var oldPolicies [][]string
	oldPolicies = l.svcCtx.Casbin.GetFilteredPolicy(0, *role.Code)
	if len(oldPolicies) != 0 {
		removeResult, err := l.svcCtx.Casbin.RemoveFilteredPolicy(0, *role.Code)
		if err != nil {
			return &types.BaseMsgResp{
				Success: false,
				Code:    errorcode.Internal,
				Msg:     err.Error(),
			}, nil
		}

		if !removeResult {
			return &types.BaseMsgResp{
				Success: false,
				Code:    errorcode.Internal,
				Msg:     l.svcCtx.Trans.Trans(l.ctx, "casbin.removeFailed"),
			}, nil
		}
	}

	//add new policies
	var policies [][]string
	for _, v := range req.Data {
		if v.Path == nil || len(*v.Path) == 0 {
			continue
		}

		if v.Method == nil || len(*v.Method) == 0 {
			continue
		}

		policies = append(policies, []string{*role.Code, *v.Path, *v.Method})
	}
	addResult, err := l.svcCtx.Casbin.AddPolicies(policies)
	if err != nil {
		return &types.BaseMsgResp{
			Success: false,
			Code:    errorcode.Internal,
			Msg:     l.svcCtx.Trans.Trans(l.ctx, "casbin.addFailed"),
		}, nil
	}

	if addResult {
		//Save the policy back to DB.
		err = l.svcCtx.Casbin.SavePolicy()
		if err != nil {
			return &types.BaseMsgResp{
				Success: false,
				Code:    errorcode.Internal,
				Msg:     l.svcCtx.Trans.Trans(l.ctx, "casbin.addFailed"),
			}, nil
		}

		return &types.BaseMsgResp{
			Success: true,
			Msg:     l.svcCtx.Trans.Trans(l.ctx, i18n.UpdateSuccess),
		}, nil
	}

	return &types.BaseMsgResp{
		Success: false,
		Code:    errorcode.Internal,
		Msg:     l.svcCtx.Trans.Trans(l.ctx, i18n.UpdateFailed),
	}, nil
}
